package com.beyond.common.util

import android.annotation.SuppressLint
import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import java.lang.reflect.InvocationTargetException

/**
 * @author chenshiyang
 * @time 2022/5/20 22:57
 * @name BoYan
 * @class describe
 */
object AppUtils {
    lateinit var instance: Application
    fun init(application: Application) {
        instance = application
        SpUtil.init(application)
    }
    var isRelease: Boolean = true
    private var activities: MutableList<AppCompatActivity> = ArrayList()
    var onResumeActivity: AppCompatActivity? = null
    fun addActivity(activity: AppCompatActivity) {
        activities.add(activity)
    }

    fun removeActivity(activity: AppCompatActivity) {
        activities.remove(activity)
    }

    fun finishAll() {
        for (activity in activities) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
    }

    /**
     * 反射获取 application
     */
    fun getApplicationByReflect(): Application {
        try {
            @SuppressLint("PrivateApi") val activityThread =
                Class.forName("android.app.ActivityThread")
            val thread = activityThread.getMethod("currentActivityThread").invoke(null)
            val app = activityThread.getMethod("getApplication").invoke(thread)
                ?: throw NullPointerException("you should init first")
            return app as Application
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        }
        throw NullPointerException("you should init first")
    }

}
